import machine
from machine import ADC, Pin,I2C, deepsleep
from machine import RTC
import utime

i2c = I2C(1, scl=Pin(18), sda=Pin(19), freq=400000)
rtc = RTC()
adc = ADC(Pin(34))
adc.atten(ADC.ATTN_11DB)  
adc.width(ADC.WIDTH_12BIT) 
rm=rtc.memory()
def gett():
    i2c.writeto(68,b"\x2c\x06")
    utime.sleep_ms(30)
    raw=i2c.readfrom(68,6)
    (t,h)=(raw[0] << 8) + raw[1], (raw[3] << 8) + raw[4]
    temp = -45 + (175 * (t / 65535))
    v=adc.read()
    v=v*7.06/4096
    return (temp,100 * (h / 65535),v)
def fw(buf):
    i2c.writeto(63,b"\x40"+buf)
def sr(x,y):
    x=x+4
    buf =b"\x00\x38" + bytes([64+y,0xe0+(x&0x0f),0xf0+((x&0xf0)>>4)])
    i2c.writeto(63,buf)
def stf(h=0,m=0):
    str=rtc.memory()
    for i in range(4):
        sr(0,i)
        fw(str[int(h/10)*64+i*16:int(h/10)*64+i*16+15])
        fw(str[int(h%10)*64+i*16:int(h%10)*64+i*16+15])
        sr(45,i)
        fw(str[int(m/10)*64+i*16:int(m/10)*64+i*16+15])
        fw(str[int(m%10)*64+i*16:int(m%10)*64+i*16+15])
def p32(str,x=0,y=6):
    for n in range(2):
        sr(x,n+y)
        for i in str:
            if ord(i)>=48 and ord(i)<=57:
                b=(ord(i)-48)*16+1499+n*8
                fw(rm[b:b+7])
            if ord(i)== 45 :
                b=(10)*16+1499+n*8
                fw(rm[b:b+7])  #-
            if ord(i) == 46:
                b=11*16+1499+n*8
                fw(rm[b:b+7])  #.
            if ord(i) == 67:
                b=14*16+1499+n*8
                fw(rm[b:b+7])  #C
            if ord(i) == 86:
                b=12*16+1499+n*8
                fw(rm[b:b+7])  #V
            if ord(i) == 37:
                b=13*16+1499+n*8
                fw(rm[b:b+7]) #%
            if ord(i) == 32:
                b=15*16+1499+n*8
                fw(rm[b:b+7]) #%
def p8(str,x=0,y=0):
    sr(x,y)
    for i in str:
        b=(ord(i)-32)*5+1024
        fw(rm[b:b+5]+b'\x00')
def st1f(t=0,r=0,u=0):
    p8("%.2fV  "%(u),80,4)
    p32("%.2fC  "%(t),0,6)
    p32("%.2f%%"%(r),80,6)
    # p32("%.2f"%(u),96,4)
da=i2c.readfrom_mem(81,2,3)
t=rtc.datetime()
s=((da[0]>>4) * 10) + (da[0]&0x0f)
m=((da[1]>>4) * 10) + (da[1]&0x0f)
h=((da[2]>>4) * 10) + (da[2]&0x0f)
stf(h,m)
st1f(*gett())
if(m==0):
    import i1
    i1.showSlow()

machine.deepsleep((60-s)*1000)